// import Stomp from "stompjs"
import { ref } from "vue";
import { WS_URL } from "@/network/constant.js";

let socketOpen = false;
let socketMsgQueue = [];
let subscribeList = [];

let heartbeat = undefined; //心跳线程

export default {
  res: ref([]),
  newitem: ref({}),
  problemRefreshBeat: ref({}),
  authbeattime: ref({}),
  blackinfo: ref({}),
  wsProblemChangeBeat: ref({}),
  videoConcatBeat: ref({}),
  myPageChangeBeat: ref({}),
  client: null,

  //   header:{
  //       login: '*****',
  //       passcode: '******',
  // // "accept-version":"1.2"
  //   },

  getBaseURL() {
    return WS_URL[wx.getAccountInfoSync().miniProgram.envVersion];
  },

  doMsg(dataStr) {
    let data = JSON.parse(dataStr);
    let topicType = null;
    if (!data.topic) {
      return;
    }
    let list = data.topic.split("/");
    topicType = list[2];
    switch (topicType) {
      case "talk":
        console.log("接收到信息-聊天");
        this.newitem.value = data;
        break;
      case "problemPageRefresh":
        console.log("接收到信息-聊天界面刷新");
        this.problemRefreshBeat.value = data;
        break;
      case "auth-change":
        this.authbeattime.value = new Date().getTime();
        console.log("接收到信息-权限变化");
        break;
      case "black":
        this.blackinfo.value = new Date().getTime();
        console.log("接收到信息-拉黑公司");
        break;
      case "blackstaff":
        this.blackinfo.value = new Date().getTime();
        console.log("接收到信息-拉黑员工");
        break;
      case "problemchange":
        console.log("接收到信息-问题变化");
        this.wsProblemChangeBeat.value = new Date().getTime();
        break;
      case "videoConcat":
        console.log("接收到信息-视频合成");
        this.videoConcatBeat.value = new Date().getTime();
        break;
      case "mypagechange":
        console.log("接收到信息-我的界面刷新");
        this.myPageChangeBeat.value = new Date().getTime();
        break;
    }
  },

  guid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
      /[xy]/g,
      function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      }
    );
  },
  getWsId() {
    if (!uni.getStorageSync("wsId")) {
      uni.setStorageSync("wsId", this.guid());
    }
    return uni.getStorageSync("wsId");
  },

  async connect() {
    // 客户端连接
    let url = (await this.getBaseURL()) + "/" + this.getWsId();
    this.client = uni.connectSocket({
      url: url,
    });
  },

  async init() {
    // 获取个随机数作为客户端连接id
    this.connect();

    uni.onSocketOpen(function (res) {
      console.log("WebSocket连接已打开！", res);
      that.subscribleList();
    });

    let that = this;
    uni.onSocketMessage(function (res) {
      console.log("收到消息：", res);
      that.doMsg(res.data);
    });

    // 连接失败
    uni.onSocketError(function (res) {
      console.log("WebSocket 连接失败！", res);
      // console.log('重新发起连接')
      // setTimeout(() => {
      // 	that.connect()
      // }, 2000);
    });

    uni.onSocketClose((res) => {
      // 网络断开
      // 后台放久了？
      console.log("WebSocket 关闭！", res);
      console.log("重新发起连接");
      setTimeout(() => {
        that.connect();
      }, 2000);
    });
  },

  subscribleList() {
    if (subscribeList) {
      subscribeList.forEach((e) => {
        this.addSubscribeTopic(e);
      });
    }
  },

  // 向后台添加添加订阅主题
  addSubscribeTopic(topic) {
    if (subscribeList.indexOf(topic) == -1) {
      subscribeList.push(topic);
    }
    let msg = JSON.stringify({ type: "xjsaddsubscribetopic", topic: topic });
    console.log("发送订阅");
    console.log("订阅主题：", topic);
    uni.sendSocketMessage({
      data: msg,
      success: (e) => {
        console.log("订阅成功", e);
      },
      fail: (e) => {
        console.log("订阅失败", e);
      },
    });
  },
  // 测试连接
  async testConnection() {
    console.log(this.client);
    if (this.client == null) {
      this.init();
    }
    // if(!this.client){
    // 	return
    // }
    // let msg = JSON.stringify({ 'type': 'xjsaddsubscribetopic', 'topic': 'testActive' })
    // console.log('测试连接是否正常')
    // uni.sendSocketMessage({
    // 	data: msg,
    // 	success: (e) => {
    // 		console.log('连接正常', e)
    // 	},
    // 	fail: (e) => {
    // 		console.log('连接异常',e)
    // 		// this.init()
    // 	}
    // });
  },

  // talk界面监听消息
  addSubscribeTalk(topic) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic("/topic/talk/" + topic);
    return;
    console.log("websocket", "开启监听", title);
    if (!subscribeList.some((t) => t.id == title)) {
      let subscribe = this.client.subscribe(title, (d) => {
        console.log("收到消息", d);
        let item = { title: d.headers.destination, body: d.body };
        this.newitem.value = item;
      });
      subscribeList.push({ id: title, value: subscribe, type: "talk" });
    }
  },

  // talk界面监听消息
  addSubscribeProblemPage(pId) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic("/topic/problemPageRefresh/" + pId);
    return;
    console.log("websocket", "开启监听", title);
    if (!subscribeList.some((t) => t.id == title)) {
      let subscribe = this.client.subscribe(title, (d) => {
        console.log("收到消息", d);
        let item = { title: d.headers.destination, body: d.body };
        this.newitem.value = item;
      });
      subscribeList.push({ id: title, value: subscribe, type: "talk" });
    }
  },

  // 监听权限变化（后端可能修改账号的权限，这里直接触发修改）
  addSubscribeAuthChange(topic) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic(topic);
    return;
    if (!subscribeList.some((t) => t.id == userid)) {
      let subscribe = this.client.subscribe(userid, (d) => {
        //let item = { title:d.headers.destination, body:d.body }
        //console.log("账号权限变化", item)
        this.authbeattime.value = new Date().getTime();
      });
      subscribeList.push({ id: userid, value: subscribe, type: "authChange" });
    }
  },

  // 监听被制造商拉黑
  addSubscribeBlack(topic) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic(topic);
    return;
    if (!subscribeList.some((t) => t.id == companyId)) {
      let subscribe = this.client.subscribe(companyId, (d) => {
        //let item = { title:d.headers.destination, body:d.body }
        console.log("被制造商拉黑");
        this.blackinfo.value = new Date().getTime();
      });
      subscribeList.push({ id: companyId, value: subscribe, type: "black" });
    }
  },

  // 监听问题变化
  addSubscribeProblemChange(topic) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic(topic);
    return;
    if (!subscribeList.some((t) => t.id == topic)) {
      let subscribe = this.client.subscribe(topic, (d) => {
        this.wsProblemChangeBeat.value = new Date().getTime();
      });
      subscribeList.push({
        id: topic,
        value: subscribe,
        type: "problemChange",
      });
    }
  },

  // 监听合成成功 id为视频脚本id
  addSubscribeVideoConcat(topic) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic(topic);
    return;
    if (!subscribeList.some((t) => t.id == id)) {
      let subscribe = this.client.subscribe(id, (d) => {
        console.log("脚本合成成功");
        this.videoConcatBeat.value = new Date().getTime();
      });
      subscribeList.push({ id: id, value: subscribe, type: "videoConcat" });
    }
  },

  // 监听我的界面的刷新
  addSubscribeMyPageChange(topic) {
    if (!this.client) {
      return;
    }
    this.addSubscribeTopic(topic);
    return;
  },

  delSubscribe(title) {
    let tmp = subscribeList.findIndex((t) => t.id == title);
    if (tmp > 0) {
      subscribeList[tmp].value.unsubscribe();
      subscribeList.splice(tmp, 1);
      console.log(subscribeList);
    }
  },
  disconnect() {
    uni.closeSocket();
  },
  sendMessage(message) {
    if (socketOpen) {
      uni.sendSocketMessage({
        data: message,
      });
    } else {
      socketMsgQueue.push(message);
    }
  },
  closeSocket() {
    console.log("closeSocket");
  },
};
